using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class 镜头跟随 : MonoBehaviour
{
    // Start is called before the first frame update
    [SerializeField]
    Transform heroTransform;
    public float maxDistance = 1;
    public float moveSpeed = 5;
    public Vector2 xRange = new Vector2(-3.1f, 3.1f);
    public Vector2 yRange = new Vector2(-2.2f, 2.2f);
    void Start()
    {
        heroTransform = GameObject.Find("Hero").transform;
        //GameObject.FindGameObjectWithTag("Player");查看标签来查找，可以分类。

    }

    // Update is called once per frame
    void Update()
    {
        UpdatePosition();
    }

    void UpdatePosition()
    {
        float newX = transform.position.x;
        float newY = transform.position.y;
        if(NeedMoveX())
        {
            //newX += Mathf.Sign(heroTransform.position.x-transform.position.x) * Time.deltaTime * moveSpeed;比下方方法不平滑
            newX =Mathf.Lerp(transform.position.x, heroTransform.position.x, Time.deltaTime * moveSpeed);
            newX =Mathf.Clamp(newX,xRange.x,xRange.y);//Clamp函数限定范围
        }
        if (NeedMoveY())
        {
            //newY += Mathf.Sign(heroTransform.position.y - transform.position.y) * Time.deltaTime * moveSpeed;
            newY = Mathf.Lerp(transform.position.y, heroTransform.position.y, Time.deltaTime * moveSpeed);
            newY = Mathf.Clamp(newY, xRange.x, xRange.y);
        }
        transform.position= new Vector3(newX,newY,transform.position.z);
    }

    bool NeedMoveX()
    {
        bool bMoveX = false;
        if(Mathf.Abs(transform.position.x-heroTransform.position.x)>maxDistance)
        {
            bMoveX = true;
        }
        return bMoveX;
    }
    bool NeedMoveY()
    {
        bool bMoveY = false;
        if (Mathf.Abs(transform.position.y - heroTransform.position.y) > maxDistance)
        {
            bMoveY = true;
        }
        return bMoveY;
    }
}
